package kim.artemis.rpc.core.util;

import cn.hutool.core.util.StrUtil;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * 工具集
 * @author Wq.
 */
public class ArtemisUtils {

    /**
     * 生成服务KEY
     * @param name
     * @param version
     * @return
     */
    public static String serviceKey(String name, String version){
        String serviceKey = name;
        if (StrUtil.isNotBlank(version)) {
            serviceKey = serviceKey.concat("#").concat(version);
        }
        return serviceKey;
    }


    /**
     * 获取网络地址
     * @return
     */
    public static String networkAddress(){
        // 本地地址，如果没有配置公网地址则返回它
        String localAddress = null;
        // 公网地址
        String newAddress = null;
        try {
            Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress inetAddress = null;
            // 是否找到公网地址
            boolean isFind = false;
            while (netInterfaces.hasMoreElements() && !isFind) {
                NetworkInterface ni = netInterfaces.nextElement();
                Enumeration<InetAddress> address = ni.getInetAddresses();
                while (address.hasMoreElements()) {
                    inetAddress = address.nextElement();
                    // 公网地址
                    if (!inetAddress.isSiteLocalAddress() && !inetAddress.isLoopbackAddress() && inetAddress.getHostAddress().indexOf(":") == -1) {
                        newAddress = inetAddress.getHostAddress();
                        isFind = true;
                        break;
                    } else if (inetAddress.isSiteLocalAddress() && !inetAddress.isLoopbackAddress()
                            && inetAddress.getHostAddress().indexOf(":") == -1) {
                        // 内网地址
                        localAddress = inetAddress.getHostAddress();
                    }
                }
            }
            if (StrUtil.isNotBlank(newAddress)) {
                return newAddress;
            } else {
                return localAddress;
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 网络地址:端口
     * @param port
     * @return
     */
    public static String networkAddressPort(int port){
        String networkAddress = networkAddress();
        if (networkAddress == null) {
            return null;
        }
        return networkAddress.concat(":").concat(String.valueOf(port));
    }

    /**
     * 网络地址:端口
     * @param port
     * @return
     */
    public static String networkAddressPort(String address, int port){
        return address.concat(":").concat(String.valueOf(port));
    }



}
